<template>
  <div>
    <el-dialog
      :title="info.isAdd ? '商品添加' : '商品修改'"
      :visible.sync="info.isshow"
      @close="close"
      @opened="opened"
    >
      {{ user }}{{attr_arr}}

      <el-form :model="user">
        <el-form-item label="一级分类" label-width="120px">
          <el-select v-model="user.first_cateid" @change="changeFirstCate">
            <!-- <el-option label="请选择" :value="0"></el-option> -->
            <el-option
              v-for="item in arr"
              :key="item.id"
              :value="item.id"
              :label="item.catename"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="二级分类" label-width="120px">
          <el-select v-model="user.second_cateid">
            <!-- <el-option label="请选择" :value="0"></el-option> -->
            <el-option
              v-for="item in secondArr"
              :key="item.id"
              :value="item.id"
              :label="item.catename"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品名称" label-width="120px">
          <el-input v-model="user.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input v-model="user.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" label-width="120px">
          <el-input v-model="user.market_price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图片" label-width="120px">
          <div class="pro">
            <h3>+</h3>
            <img :src="imgUrl" v-if="imgUrl" />
            <input type="file" @change="getFile" />
          </div>
        </el-form-item>

        <el-form-item label="商品规格" label-width="120px">
          <el-select v-model="user.specsid" @change="changeSpecs">
            <el-option
              :label="item.specsname"
              :value="item.id"
              v-for="item in specsArr"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="规格属性" label-width="120px">
          <el-select v-model="user.specsattr" multiple>
            <el-option
              :label="item"
              :value="item"
              v-for="item in attr_arr"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否新品" label-width="120px">
          <el-radio v-model="user.isnew" :label="1">是</el-radio>
          <el-radio v-model="user.isnew" :label="2">否</el-radio>
        </el-form-item>

        <el-form-item label="是否热卖" label-width="120px">
          <el-radio v-model="user.ishot" :label="1">是</el-radio>
          <el-radio v-model="user.ishot" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="user.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
        <el-form-item label="商品描述">
          <!-- <el-input type="textarea" v-model="user.description"></el-input> -->
        <div id="editor" v-if="info.isshow"></div>
        </el-form-item>
      </el-form>
      <!-- </el-form> -->

      <div slot="footer" class="dialog-footer">
        <el-button>取 消</el-button>
        <el-button type="primary" v-if="info.isAdd" @click="add"
          >添 加</el-button
        >
        <el-button type="primary" v-else @click="edit">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqcateadd,
  reqcatelist,
  reqcateinfo,
  reqcateedit,
  reqspecslist,
  reqgoodsadd,
  reqgoodsinfo
} from "../../../http/api";
import path from "path";
import E from 'wangeditor'
import { successAlert, errorAlert } from "../../../utils";
import {reqgoodsedit} from '../../../http/api'
export default {
  props: ["info"],
  methods: {
    opened(){
      this.editor = new E("#editor");
      this.editor.create();

      this.editor.txt.html(this.user.description);
    },
    getFile(e) {
      let file = e.target.files[0];
      //验证大小 file.size 单位是B    1M=1024KB 1KB=1024B 1B=8b
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件最大2M");
        return;
      }

      let imgArr = [".png", ".jpeg", ".jpg", ".gif"];
      let extname = path.extname(file.name); // .png
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }
      // 生成图片地址
      this.imgUrl = URL.createObjectURL(file);
      //存到user，后续发送给后端
      this.user.img = file;
      console.log(this.user.img);
    },
    // 选了一级分类
    changeFirstCate() {
      this.user.second_cateid = "";
      this.get_second_cate_list()
    },
    get_second_cate_list(){
         reqcatelist({ pid: this.user.first_cateid }).then((res) => {
        this.secondArr = res.data.list;
      });
    },
    empty() {
      this.user = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: "",
        isnew: 2,
        ishot: 2,
        status: 1,
      };
      //二级分类的列表
      this.secondArr = [];
      //规格属性的列表
      this.attr_arr = [];
      //清除图片
      // this.$refs.upload.setImgUrl("");
    },
    getOne(id){
      reqgoodsinfo({id}).then(res => {
        // console.log('获取一条',res);
        this.user = res.data.list
        this.user.id = id;
        this.get_second_cate_list()
        this.user.specsattr = this.user.specsattr.split(',');
        this.$emit('init');
        this.imgUrl = this.$pre + this.user.img;
        if (this.editor) {
            this.editor.txt.html(this.user.description); // 重新设置编辑器内容
          }
      })
    },
    add() {
      reqgoodsadd({
        ...this.user,
        specsattr: this.user.specsattr.join(","),
        description: this.editor.txt.html(), //富文本编辑器的内容赋值给description
      }).then((res) => {
        // console.log('add',res);
        successAlert(res.data.msg);
        this.empty();
        this.info.isshow = false;

      });
    },
    // 修改规格之后
    changeSpecs() {
      this.user.specsattr = [];
      // reqspecslist().then((res) => {
      //   // console.log(res);
      // });
      let obj = this.specsArr.find((item) => item.id == this.user.specsid);
      this.attr_arr = obj ? obj.attrs : [];
    },
    getSpecsList() {
      // 规格列表
      reqspecslist().then((res) => {
        // console.log(res);
        this.specsArr = res.data.list;
      });
    },
    // 请求分类
    getCateList() {
      // 一级分类
      reqcatelist({ istree: true, pid: this.user.first_cateid }).then((res) => {
        this.arr = res.data.list;
      });
    },
    edit(){
      reqgoodsedit({...this.user,specsattr: this.user.specsattr.join(","),}).then(res => {
        // console.log('编辑',res);
        successAlert(res.data.msg);
        this.empty();
        this.info.isshow = false;
        this.$emit('init')
      })
    },
    close(){
      if(!this.info.isAdd){
        this.empty()
      }
    }
  },
  mounted() {
    // 请求分类数据
    this.getCateList();
    // 请求规格
    this.getSpecsList();
  },

  data() {
    return {
      user: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      total: 0,
      page: 1,
      size: 2,
      imgUrl: "",
      // 一级分类
      arr: [],
      //二级分类的列表
      secondArr: [],
      //商品规格的列表
      specsArr: [],
      // 商品属性列表
      attr_arr: [],
    };
  },
};
</script>

<style scoped>
.pro {
  width: 200px;
  height: 200px;
  border: 1px solid #000;
  position: relative;
}
.pro input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  opacity: 0;
}
.pro img {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
.pro h3 {
  text-align: center;
  line-height: 200px;
}
</style>